package pannel.user;

import system.BasePage;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.sql.SQLException;
import java.util.*;
import java.util.List;

public class UserManagementPage extends BasePage {
    private static final Map<String, Set<String>> BUTTON_ROLE_MAPPING = new HashMap<>();
    private DefaultTableModel model;
    private List<User> userList = new ArrayList<>();
    private JTable table;
    private JTextField searchField;
    private int currentPage = 1;
    private int pageSize = 10;
    private JLabel pageInfoLabel;
    private UserDao userDao;
    private int totalRecords = 0;

    static {
        BUTTON_ROLE_MAPPING.put("addButton", new HashSet<>(Arrays.asList(User.ROLE_ADMIN)));
        BUTTON_ROLE_MAPPING.put("deleteButton", new HashSet<>(Collections.singletonList(User.ROLE_ADMIN)));
        BUTTON_ROLE_MAPPING.put("editButton", new HashSet<>(Arrays.asList(User.ROLE_ADMIN)));
    }

    private static class NonEditableTableModel extends DefaultTableModel {
        public NonEditableTableModel(Object[][] data, Object[] columnNames) {
            super(data, columnNames);
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            if (columnIndex == 0) return ImageIcon.class;
            return super.getColumnClass(columnIndex);
        }
    }

    public UserManagementPage(User user) {
        super(user);
        userDao = new UserDao();
        initPageContent();
    }

    @Override
    protected void initPageContent() {
        setPageTitle("用户管理");
        setupContent();
        refreshTable();
    }

    private static class ImageRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus,
                                                       int row, int column) {
            if (value instanceof ImageIcon) {
                JLabel label = new JLabel((ImageIcon) value);
                label.setHorizontalAlignment(JLabel.CENTER);
                if (isSelected) {
                    label.setBackground(table.getSelectionBackground());
                    label.setOpaque(true);
                } else {
                    label.setOpaque(false);
                }
                return label;
            }
            return super.getTableCellRendererComponent(table, value, isSelected,
                    hasFocus, row, column);
        }
    }

    private static ImageIcon createScaledImageIcon(String path) {
        try {
            File imageFile = new File(path);
            if (!imageFile.exists() || !imageFile.isFile()) {
                throw new Exception("Image file does not exist: " + path);
            }

            ImageIcon originalIcon = new ImageIcon(path);
            if (originalIcon.getIconWidth() == -1) {
                throw new Exception("Invalid image file");
            }

            Image image = originalIcon.getImage();
            Image scaledImage = image.getScaledInstance(40, 40, Image.SCALE_SMOOTH);
            return new ImageIcon(scaledImage);
        } catch (Exception e) {
            return createDefaultIcon();
        }
    }

    private static ImageIcon createDefaultIcon() {
        BufferedImage defaultImage = new BufferedImage(40, 40, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = defaultImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setColor(Color.LIGHT_GRAY);
        g2d.fillOval(0, 0, 39, 39);
        g2d.setColor(Color.GRAY);
        g2d.drawOval(0, 0, 39, 39);
        g2d.dispose();
        return new ImageIcon(defaultImage);
    }

    private JButton createRoleButton(String buttonText, String buttonId) {
        JButton button = new JButton(buttonText);
        Set<String> allowedRoles = BUTTON_ROLE_MAPPING.getOrDefault(buttonId, Collections.emptySet());
        button.setVisible(allowedRoles.contains(getCurrentUser().getRole()));
        return button;
    }

    private void refreshTable() {
        SwingUtilities.invokeLater(() -> {
            try {
                String searchText = searchField.getText().trim();
                userList = userDao.pageQuery(searchText, currentPage, pageSize);
                totalRecords = userDao.getTotalCount(searchText);

                model.setRowCount(0);
                for (User user : userList) {
                    model.addRow(new Object[]{
                            createScaledImageIcon(user.getAvatarPath()),
                            user.getId(),
                            user.getUsername(),
                            user.getRole()
                    });
                }
                updatePageInfo();
                table.repaint();
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(this, "获取用户数据失败：" + e.getMessage());
            }
        });
    }

    private void updatePageInfo() {
        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
        pageInfoLabel.setText(String.format("第 %d/%d 页  共%d条记录", currentPage, totalPages, totalRecords));
    }private void setupContent() {
        contentArea.setLayout(new BorderLayout());
        JPanel topPanel = new JPanel(new BorderLayout());

        // 搜索面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchField = new JTextField(20);
        JButton searchButton = new JButton("搜索");
        searchPanel.add(new JLabel("用户名："));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);

        // 工具栏
        JPanel toolBar = new JPanel(new FlowLayout(FlowLayout.LEFT));
        toolBar.setBackground(Color.WHITE);

        JButton addButton = createRoleButton("新增用户", "addButton");
        JButton deleteButton = createRoleButton("删除用户", "deleteButton");
        JButton editButton = createRoleButton("编辑用户", "editButton");

        toolBar.add(addButton);
        toolBar.add(deleteButton);
        toolBar.add(editButton);

        topPanel.add(searchPanel, BorderLayout.NORTH);
        topPanel.add(toolBar, BorderLayout.CENTER);

        // 表格设置
        String[] columnNames = {"头像", "ID", "账号", "角色"};
        model = new NonEditableTableModel(new Object[0][], columnNames);
        table = new JTable(model);

        table.getTableHeader().setReorderingAllowed(false);
        TableColumn avatarColumn = table.getColumnModel().getColumn(0);
        avatarColumn.setCellRenderer(new ImageRenderer());
        avatarColumn.setPreferredWidth(50);
        table.setRowHeight(45);
        table.getColumnModel().getColumn(1).setPreferredWidth(50);
        table.getColumnModel().getColumn(2).setPreferredWidth(100);
        table.getColumnModel().getColumn(3).setPreferredWidth(80);

        // 分页面板
        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton prevButton = new JButton("上一页");
        JButton nextButton = new JButton("下一页");
        pageInfoLabel = new JLabel();

        paginationPanel.add(prevButton);
        paginationPanel.add(pageInfoLabel);
        paginationPanel.add(nextButton);

        // 按钮事件处理
        prevButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                refreshTable();
            }
        });

        nextButton.addActionListener(e -> {
            int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
            if (currentPage < totalPages) {
                currentPage++;
                refreshTable();
            }
        });

        searchButton.addActionListener(e -> {
            currentPage = 1;
            refreshTable();
        });

        addButton.addActionListener(e -> {
            UserDialog dialog = new UserDialog(null, "新增用户", null);
            if (dialog.showDialog()) {
                try {
                    User newUser = User.builder()
                            .username(dialog.getUsername())
                            .password(dialog.getPassword())
                            .role(dialog.getRole())
                            .avatarPath(dialog.getAvatarPath())
                            .build();

                    if (userDao.insert(newUser)) {
                        JOptionPane.showMessageDialog(this, "添加用户成功！");
                        refreshTable();
                    } else {
                        JOptionPane.showMessageDialog(this, "添加用户失败！");
                    }
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(this, "添加用户失败：" + ex.getMessage());
                }
            }
        });

        deleteButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                int id = (Integer) table.getValueAt(selectedRow, 1);
                int confirm = JOptionPane.showConfirmDialog(this,
                        "确定要删除该用户吗？", "确认删除",
                        JOptionPane.YES_NO_OPTION);

                if (confirm == JOptionPane.YES_OPTION) {
                    try {
                        if (userDao.deleteById(id)) {
                            JOptionPane.showMessageDialog(this, "删除成功！");
                            refreshTable();
                        } else {
                            JOptionPane.showMessageDialog(this, "删除失败！");
                        }
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "删除失败：" + ex.getMessage());
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "请选择要删除的用户");
            }
        });

        editButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                User selectedUser = userList.get(selectedRow);
                UserDialog dialog = new UserDialog(null, "编辑用户", selectedUser);
                if (dialog.showDialog()) {
                    try {
                        selectedUser.setUsername(dialog.getUsername());
                        selectedUser.setPassword(dialog.getPassword());
                        selectedUser.setRole(dialog.getRole());
                        selectedUser.setAvatarPath(dialog.getAvatarPath());

                        if (userDao.updateById(selectedUser)) {
                            JOptionPane.showMessageDialog(this, "更新成功！");
                            refreshTable();
                        } else {
                            JOptionPane.showMessageDialog(this, "更新失败！");
                        }
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "更新失败：" + ex.getMessage());
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "请选择要编辑的用户");
            }
        });

        JScrollPane scrollPane = new JScrollPane(table);
        contentArea.add(topPanel, BorderLayout.NORTH);
        contentArea.add(scrollPane, BorderLayout.CENTER);
        contentArea.add(paginationPanel, BorderLayout.SOUTH);
    }
}

class UserDialog extends JDialog {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JComboBox<String> roleComboBox;
    private JTextField avatarPathField;
    private JButton browseButton;
    private boolean confirmed = false;
    private User user;
    private JLabel previewLabel;

    public UserDialog(Frame owner, String title, User user) {
        super(owner, title, true);
        this.user = user;
        setupDialog();
    }

    private void setupDialog() {
        setLayout(new BorderLayout());
        JPanel mainPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 用户名
        addField(mainPanel, gbc, "用户名:", usernameField = new JTextField(20), 0);

        // 密码
        addField(mainPanel, gbc, "密码:", passwordField = new JPasswordField(20), 1);

        // 角色
        roleComboBox = new JComboBox<>(User.ROLES.toArray(new String[0]));
        addField(mainPanel, gbc, "角色:", roleComboBox, 2);

        // 头像路径
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 1;
        mainPanel.add(new JLabel("头像路径:"), gbc);

        avatarPathField = new JTextField(20);
        gbc.gridx = 1;
        gbc.gridwidth = 1;
        mainPanel.add(avatarPathField, gbc);

        browseButton = new JButton("浏览");
        gbc.gridx = 2;
        mainPanel.add(browseButton, gbc);

        // 预览
        previewLabel = new JLabel();
        previewLabel.setPreferredSize(new Dimension(100, 100));
        previewLabel.setHorizontalAlignment(JLabel.CENTER);
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridwidth = 3;
        mainPanel.add(previewLabel, gbc);

        // 填充现有数据
        if (user != null) {
            usernameField.setText(user.getUsername());
            passwordField.setText(user.getPassword());
            roleComboBox.setSelectedItem(user.getRole());
            avatarPathField.setText(user.getAvatarPath());
            updatePreview(user.getAvatarPath());
        }

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton okButton = new JButton("确定");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(okButton);
        buttonPanel.add(cancelButton);

        // 事件处理
        browseButton.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
                public boolean accept(File f) {
                    String name = f.getName().toLowerCase();
                    return f.isDirectory() || name.endsWith(".jpg") || name.endsWith(".png")
                            || name.endsWith(".gif") || name.endsWith(".jpeg");
                }

                public String getDescription() {
                    return "Image Files (*.jpg, *.png, *.gif, *.jpeg)";
                }
            });

            if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                String path = fileChooser.getSelectedFile().getAbsolutePath();
                avatarPathField.setText(path);
                updatePreview(path);
            }
        });

        okButton.addActionListener(e -> {
            if (validateInput()) {
                confirmed = true;
                dispose();
            }
        });

        cancelButton.addActionListener(e -> dispose());

        add(mainPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    private void addField(JPanel panel, GridBagConstraints gbc, String label, JComponent component, int y) {
        gbc.gridx = 0;
        gbc.gridy = y;
        gbc.gridwidth = 1;
        panel.add(new JLabel(label), gbc);

        gbc.gridx = 1;
        gbc.gridwidth = 2;
        panel.add(component, gbc);
    }

    private boolean validateInput() {
        String username = usernameField.getText().trim();
        String password = new String(passwordField.getPassword()).trim();
        String avatarPath = avatarPathField.getText().trim();

        if (username.isEmpty()) {
            JOptionPane.showMessageDialog(this, "用户名不能为空");
            return false;
        }

        if (password.isEmpty()) {
            JOptionPane.showMessageDialog(this, "密码不能为空");
            return false;
        }

        if (avatarPath.isEmpty() || !new File(avatarPath).exists()) {
            JOptionPane.showMessageDialog(this, "请选择有效的头像文件");
            return false;
        }

        return true;
    }

    private void updatePreview(String imagePath) {
        try {
            ImageIcon originalIcon = new ImageIcon(imagePath);
            Image image = originalIcon.getImage();
            Image scaledImage = image.getScaledInstance(100, 100, Image.SCALE_SMOOTH);
            previewLabel.setIcon(new ImageIcon(scaledImage));
        } catch (Exception e) {
            previewLabel.setIcon(null);
            previewLabel.setText("预览失败");
        }
    }

    public boolean showDialog() {
        setVisible(true);
        return confirmed;
    }

    public String getUsername() {
        return usernameField.getText().trim();
    }

    public String getPassword() {
        return new String(passwordField.getPassword()).trim();
    }

    public String getRole() {
        return (String) roleComboBox.getSelectedItem();
    }

    public String getAvatarPath() {
        return avatarPathField.getText().trim();
    }
}